"BigTable cache backend"

from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
from django.utils.encoding import smart_unicode, smart_str
from google.appengine.ext import db
import pickle, base64

class Cache(db.Model):
    cache_key = db.StringProperty()
    cache_value = db.BlobProperty()
    
    def set(self, value):
        self.cache_value = pickle.dumps(value)

    def get(self):
        if not self.cache_value: return None
        return pickle.loads(self.cache_value)

class CacheClass(BaseCache):
    def __init__(self, server, params):
        BaseCache.__init__(self, params)

    def add(self, key, value, timeout=0):
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        c = db.Query(Cache).filter("cache_key =",smart_str(key)).get()
        if not c: c = Cache(cache_key=key)
        c.set(value)

    def get(self, key, default=None):
        val = db.Query(Cache).filter("cache_key =",smart_str(key)).get()
        if val is None:
            return default
        else:
            val = val.get()
            if isinstance(val, basestring):
                return smart_unicode(val)
            else:
                return val

    def set(self, key, value, timeout=0):
        if isinstance(value, unicode):
            value = value.encode('utf-8')
        c = db.Query(Cache).filter("cache_key =",key).get()
        if not c: c = Cache(cache_key=key)
        c.set(value)
        c.put()

    def delete(self, key):
        c = db.Query(Cache).filter("cache_key =",key).get()
        if c: c.delete()

    def get_many(self, keys):
        d = {}
	for key in keys:
            d[key] = self.get(key)
        return d
